import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class Client {
	static ObjectOutputStream out;
	static ObjectInputStream in;
	static ArrayList<Book> Books;
	private static Socket s;
	private String name;

	public Client(String name){this.name=name;}

	private Object receiveObject ( ) throws ClassNotFoundException
	{
		Object received = null;

		try{
			received = in.readObject();
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}

		return received;
	}

	private void sendObject ( Object obj)
	{
		try{
			out.writeObject(obj);
			out.flush();
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}

	public void send(Object o) throws ClassNotFoundException{
		connect();
		sendObject(o);
		disconnect();
	}

	public Object receive(Object o) throws ClassNotFoundException{
		connect();
		Object ob = receiveObject();
		disconnect();
		return ob;
	}

	private void connect() throws ClassNotFoundException{
		System.out.println("Initializing Client...");

		try {
			System.out.println("Connecting on Library Server.");    
			s = new Socket("localhost", 20009);
			System.out.println("You are connected on Library.");

			out = new ObjectOutputStream(s.getOutputStream());
			in = new ObjectInputStream(s.getInputStream());

			sendObject(new Integer(1));

			sendObject(this.name);
			
			String response = (String) receiveObject();

		} catch (IOException e) {
			System.out.println("Troubles on Server => " + e.getMessage());
		}
	}

	private void disconnect(){
		try {
			s.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void searchBooks(){
		try{
			connect();
			String r=(String)receiveObject();
			System.out.println("===> "+r);
			sendObject(1);
			ArrayList<Book> books = (ArrayList<Book>)receiveObject();
			for(Book b : books){
				b.showBook();
			}
			disconnect();
		} catch (Exception e){}
	}
	
	public void borrowBook(int id){
		try{
			Book aux = new Book(id);
			connect();
			sendObject(2);
			sendObject(aux);
			String response = (String)receiveObject();
			System.out.println(response);
			disconnect();
		} catch (Exception e){}
	}
	
	public void returnBook(int id){
		try{
			Book aux = new Book(id);
			connect();
			sendObject(3);
			sendObject(aux);
			String response = (String)receiveObject();
			System.out.println(response);
			disconnect();
		} catch (Exception e){}
	}
	
	public ArrayList<Book> getBooks(){
		ArrayList<Book> books = null;
		try{
			connect();
			sendObject(1);
			books = (ArrayList<Book>)receiveObject();
			disconnect();
		} catch (Exception e){}
		return books;
	}
}
